﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace DataCenter.Share
{
    public class RecordCollection : List<BinaryRecord>, IEnumerable, IEnumerator
    {
        public RecordCollection(int step, int[] operTypes)
        {
            this.Step = step;
            this.OperTypes = operTypes;
        }

        private int CurIndex;
        private BinaryRecord CurRecord;
        private IIterator CurIterator;
        private ResultRecordRow _Row;
        private int Step;
        private int[] OperTypes;

        #region IEnumerable Members

        public new IEnumerator GetEnumerator()
        {
            Reset();
            return this;
        }

        #endregion

        #region IEnumerator Members

        public object Current
        {
            get 
            {
                _Row.ObjectId = CurRecord.ObjectId;
                _Row.ValueType = CurRecord.ValueType;
                return _Row; 
            }
        }

        public bool MoveNext()
        {
            if (CurIterator != null)
            {
                if (CurIterator.MoveNext())
                {
                    _Row = (ResultRecordRow)CurIterator.Current;
                    return true;
                }
            }

            CurIndex += 1;
            if (CurIndex < this.Count)
            {
                CurRecord = this[CurIndex];

                Binary binaryValue = CurRecord.BinaryValue;
                binaryValue.BeginEdit();

                CurIterator = (IIterator)binaryValue;
                CurIterator.Step = Step;
                CurIterator.OperTypes = OperTypes;
                CurIterator.Reset();

                if (CurIterator.MoveNext())
                {
                    _Row = (ResultRecordRow)CurIterator.Current;
                    return true;
                }
            }
            else
            {
                return false;
            }

            Binary.ReleaseCache();
            return false;
        }

        public void Reset()
        {
            CurIndex = -1;
            CurRecord = null;
            CurIterator = null;            
        }

        #endregion
    }
}
